package com.mall.controller;


import com.mall.entity.Coupon;
import com.mall.entity.UserCoupon;
import com.mall.pojo.ResponseMessage;
import com.mall.service.ICouponService;
import com.mall.service.IUserCouponService;
import com.mall.util.DateUtils;
import com.mall.util.UserUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 优惠券表 前端控制器
 * </p>
 * @author sppxpp
 * @since 2023-04-16
 */
@RestController
@RequestMapping("/user/coupon")
@CrossOrigin
public class CouponController {
    final
    IUserCouponService userCouponService;
    final
    ICouponService couponService;

    public CouponController(ICouponService couponService, IUserCouponService userCouponService) {
        this.couponService = couponService;
        this.userCouponService = userCouponService;
    }

    @GetMapping
    public ResponseMessage queryCoupon(){
        return ResponseMessage.success(couponService.queryCoupon());
    }

    //查询我的优惠券
    @GetMapping("/my")
    public ResponseMessage queryMyCoupon(@RequestParam Boolean flag,HttpServletRequest request){
        return ResponseMessage.success(userCouponService.queryCoupon(flag, UserUtils.userId(request)));
    }

    //查询我的优惠券
    @GetMapping("/canUseCount")
    public ResponseMessage queryCouponCount(HttpServletRequest request){
        return ResponseMessage.success(userCouponService.queryCouponCount(UserUtils.userId(request)));
    }

    @PostMapping
    public ResponseMessage addCoupon(@RequestParam Integer couponId, HttpServletRequest request){
        Coupon coupon = couponService.queryCouponById(couponId);
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(UserUtils.userId(request));
        userCoupon.setCouponId(couponId);
        userCoupon.setCouponStatus(false);
        userCoupon.setCouponExpireTime(DateUtils.addDays(coupon.getCouponExpiryDate()));
        try {
            return userCouponService.claimCoupon(userCoupon) ? ResponseMessage.success() : ResponseMessage.custom("-1","领取优惠券失败！");
        }catch (Exception e){
            return ResponseMessage.custom("-1","你已经领取过该优惠券！");
        }
    }

    //查询我的优惠券
    @GetMapping("/my/expired")
    public ResponseMessage queryMyExpiredCoupon(HttpServletRequest request){
        return ResponseMessage.success(userCouponService.queryExpiredCoupon( UserUtils.userId(request)));
    }

    @DeleteMapping
    public ResponseMessage deleteCoupon(@RequestBody List<Integer> ids){
        return ResponseMessage.success(userCouponService.deleteCoupon(ids));
    }
}

